package com.mercycrazy.recruit.rabbit;

import com.alibaba.fastjson2.JSON;
import com.mercycrazy.recruit.retry.RetrySMSService;
import com.mercycrazy.recruit.vo.mq.SendSMS;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.mercycrazy.recruit.constant.RabbitMQConstant.SMS_LOGIN_SEND_ROUTING;
import static com.mercycrazy.recruit.constant.RabbitMQConstant.SMS_QUEUE;

/**
 * Rabbit 短信发送相关消息的消费
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-19
 */
@Component
@Slf4j
public class RabbitMQSMSConsumer {

    private final RetrySMSService retrySMSService;

    public RabbitMQSMSConsumer(RetrySMSService retrySMSService) {
        this.retrySMSService = retrySMSService;
    }

    @RabbitListener(queues = {SMS_QUEUE})
    public void watchQueue(String payload, Channel channel, Message message) throws Exception {

        try {
            SendSMS sendSMS = JSON.parseObject(payload, SendSMS.class);
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();

            log.info("consumer message from queue: [{}], payload: [{}], routingKey: [{}]",
                    SMS_QUEUE, payload, routingKey);

            if (Objects.equals(routingKey, SMS_LOGIN_SEND_ROUTING)) {
                Boolean success = retrySMSService.sendSMSWithRetry(sendSMS);
                if (!success) {
                    log.error("send login sms failed, mobile: [{}], code: [{}}",
                            sendSMS.getPhone(), sendSMS.getContent());
                }
            }

            // deliveryTag: 消息投递的标签
            // multiple: 批量确认所有消费者获得的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            e.printStackTrace();
            // requeue: 是否重回队列 true: 重新回到队列, false: 丢弃消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                    true, true);
        }
    }
}
